package com.lyshop.jinding.activitys;

import static com.lyshop.jinding.eventbus.EventConstants.EVENTCODE_UPDATE_USER;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.gamerole.orcameralib.CameraActivity;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.lyshop.jinding.R;
import com.lyshop.jinding.base.BaseActivity;
import com.lyshop.jinding.bean.CredentialBean;
import com.lyshop.jinding.bean.UserIdCardBean;
import com.lyshop.jinding.bean.UserInfoBean;
import com.lyshop.jinding.eventbus.EventCenter;
import com.lyshop.jinding.net.ActionCallbackListener;
import com.lyshop.jinding.qcloud.QCloudUtil;
import com.lyshop.jinding.utils.CustomerUtil;
import com.lyshop.jinding.utils.DataUtils;
import com.lyshop.jinding.utils.FastClickUtil;
import com.lyshop.jinding.utils.LogUtil;
import com.lyshop.jinding.utils.RouteUtil;
import com.lyshop.jinding.utils.ToastUtil;
import com.lyshop.jinding.view.ConfirmUserInfoDialog;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class CertificateIdCardActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_right;
    private RelativeLayout rl_front;
    private RelativeLayout rl_back;
    private ImageView iv_idcard_front;
    private ImageView iv_idcard_back;
    private Button bt_submit;
    private int mImageIndex;//前后照片 0前 1后
    public static File mFrontIdCard = new File(Environment.getExternalStorageDirectory(),
            "id_card_front.jpg");//前边存储位置
    public static File mBackIdCard = new File(Environment.getExternalStorageDirectory(),
            "id_card_back.jpg");//后边存储位置
    private final int REQUEST_CODE_ALBUM = 101;//相册回调
    private final int REQUEST_CODE_CAMER = 102;//相机回调
    private final int REQUEST_CODE_CROP = 103;//裁剪回调
    //    private String frontBase64 = "";
//    private String backBase64 = "";
    private String frontCosUrl = "";
    private String backCosUrl = "";
    //权限code
    private int ALL_PERMISSION = 1000;
    private ConfirmUserInfoDialog mConfirmDialog;
    private UserIdCardBean mUserIdCardBean;

    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.CAMERA,
            Manifest.permission.MANAGE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_certificate_id_card;
    }

    @Override
    protected void findViews() {
        iv_right = findViewById(R.id.iv_right);
        rl_front = findViewById(R.id.rl_front);
        rl_back = findViewById(R.id.rl_back);
        iv_idcard_front = findViewById(R.id.iv_idcard_front);
        iv_idcard_back = findViewById(R.id.iv_idcard_back);
        bt_submit = findViewById(R.id.bt_submit);
    }

    @Override
    protected void setListeners() {
        iv_right.setOnClickListener(this);
        rl_front.setOnClickListener(this);
        rl_back.setOnClickListener(this);
        bt_submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_right:
                CustomerUtil.customerService(this);
                break;
            case R.id.rl_front:
                mImageIndex = 0;
                showDialog();
                break;
            case R.id.rl_back:
                mImageIndex = 1;
                showDialog();
                break;
            case R.id.bt_submit:
                doCertificate();
                break;
        }
    }

    /**
     * 显示选择相册和相机的弹窗
     */
    private void showDialog() {
        if (!FastClickUtil.isFastClick()) {
            requestWritePermission();
        }
    }

    private void requestWritePermission() {
        if (XXPermissions.isGranted(mContext, REQUIRED_PERMISSIONS)){
            if (mImageIndex == 0) {
                Intent intent = new Intent(CertificateIdCardActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, mFrontIdCard.getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMER);
            } else {
                Intent intent = new Intent(CertificateIdCardActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, mBackIdCard.getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                startActivityForResult(intent, REQUEST_CODE_CAMER);
            }
        }else {
            XXPermissions.with(this)
                    // 申请多个权限
                    .permission(REQUIRED_PERMISSIONS)
                    // 设置权限请求拦截器（局部设置）
                    //.interceptor(new PermissionInterceptor())
                    // 设置不触发错误检测机制（局部设置）
                    //.unchecked()
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            if (!allGranted) {
                                ToastUtil.showToast(mContext, "获取部分权限成功，但部分权限未正常授予");
                                return;
                            }
                            if (mImageIndex == 0) {
                                Intent intent = new Intent(CertificateIdCardActivity.this, CameraActivity.class);
                                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, mFrontIdCard.getAbsolutePath());
                                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                                startActivityForResult(intent, REQUEST_CODE_CAMER);
                            } else {
                                Intent intent = new Intent(CertificateIdCardActivity.this, CameraActivity.class);
                                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, mBackIdCard.getAbsolutePath());
                                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                                startActivityForResult(intent, REQUEST_CODE_CAMER);
                            }
                        }

                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                            if (doNotAskAgain) {
                                ToastUtil.showToast(mContext,"被永久拒绝授权，请手动授予录音和日历权限");
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                XXPermissions.startPermissionActivity(mContext, permissions);
                            } else {
                                ToastUtil.showToast(mContext,"获取录音和日历权限失败");
                            }
                        }
                    });

        }

    }


    /**
     * 照片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_ALBUM://相册
                showImageByUri(data.getData());
                break;
            case REQUEST_CODE_CAMER://相机
                if (mImageIndex == 0) {
                    showImageByUri(Uri.fromFile(mFrontIdCard));
                } else {
                    showImageByUri(Uri.fromFile(mBackIdCard));
                }
                break;
            case REQUEST_CODE_CROP://裁剪完成
                if (mImageIndex == 0) {
                    Drawable fromPath = BitmapDrawable.createFromPath(mFrontIdCard.getAbsolutePath());
                    iv_idcard_front.setImageDrawable(fromPath);
//                    Glide.with(this).load(mFrontIdCard).apply(mRoundOptions).into(iv_idcard_front);
                } else {
//                    Glide.with(this).load(mBackIdCard).apply(mRoundOptions).into(iv_idcard_back);
                    Drawable fromPath = BitmapDrawable.createFromPath(mBackIdCard.getAbsolutePath());
                    iv_idcard_back.setImageDrawable(fromPath);
                }
                break;
        }
    }

    /**
     * 显示照片
     *
     * @param uri
     */
    private void showImageByUri(Uri uri) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            if (mImageIndex == 0) {
                iv_idcard_front.setImageBitmap(bitmap);
//                frontBase64 = CameraUtil.bitmapToBase64(bitmap);
            } else {
                iv_idcard_back.setImageBitmap(bitmap);
//                backBase64 = CameraUtil.bitmapToBase64(bitmap);
            }
            toUpload();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void toUpload() {
        loading();
        mAppAction.getCosUpload(new ActionCallbackListener<CredentialBean>() {
            @Override
            public void onSuccess(CredentialBean data) {
                CredentialBean.Temp temp = data.temp;
                CredentialBean.Credentials credentials = temp.credentials;
                String path = mImageIndex == 0 ? mFrontIdCard.getAbsolutePath() : mBackIdCard.getAbsolutePath();
                QCloudUtil.toCos(mContext, mImageIndex == 0, data.region, path, data.bucket, credentials.tmpSecretId, credentials.tmpSecretKey, credentials.sessionToken, temp.startTime, temp.expiredTime, new CosXmlResultListener() {
                    @Override
                    public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                        cancelLoading();
                        if (mImageIndex == 0) {
                            frontCosUrl = result.accessUrl;
                        } else {
                            backCosUrl = result.accessUrl;
                        }
                    }

                    @Override
                    public void onFail(CosXmlRequest request, @Nullable CosXmlClientException clientException, @Nullable CosXmlServiceException serviceException) {
                        cancelLoading();
                        if (clientException != null) {
                            clientException.printStackTrace();
                        } else {
                            serviceException.printStackTrace();
                        }
                    }
                });

            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    private File createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 身份证认证
     */
    private void doCertificate() {
        if (TextUtils.isEmpty(frontCosUrl) || TextUtils.isEmpty(backCosUrl)) {
            ToastUtil.showToast(this, "请先完成身份证件上传");
            return;
        }
        LogUtil.d("前url:" + frontCosUrl + "===后url:" + backCosUrl);
        loading();
        mAppAction.uploadCert(backCosUrl, frontCosUrl, new ActionCallbackListener<UserIdCardBean>() {
            @Override
            public void onSuccess(UserIdCardBean data) {
                cancelLoading();
                mUserIdCardBean = data;
                showCertConfirmDialog(data);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, "身份信息有误，请重新上传");
            }
        });
    }

    /**
     * 信息确认弹窗
     *
     * @param bean
     */
    private void showCertConfirmDialog(UserIdCardBean bean) {
        mConfirmDialog = new ConfirmUserInfoDialog(this, new ConfirmUserInfoDialog.ConfirmListener() {
            @Override
            public void onConfirm(String name, String cert_no) {
                uploadCertConfirm(name);
            }
        });
        mConfirmDialog.init(bean);
        if (!mConfirmDialog.isShowing()) {
            mConfirmDialog.show();
        }
    }

    /**
     * 二次信息确认
     *
     * @param name
     */
    private void uploadCertConfirm(String name) {
        if (null != mUserIdCardBean) {
            loading();
            mAppAction.uploadCertConfirm(name, mUserIdCardBean.request_id, new ActionCallbackListener<Void>() {
                @Override
                public void onSuccess(Void data) {
                    myApplication.updateUserDetail();
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    cancelLoading();
                    if (null != mConfirmDialog) {
                        mConfirmDialog.dismiss();
                    }
                    ToastUtil.showToast(CertificateIdCardActivity.this, message);
                }
            });
        } else {
            ToastUtil.showToast(mContext, "请先上传身份证件信息");
        }
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int eventCode = eventCenter.getEventCode();
        switch (eventCode) {
            case EVENTCODE_UPDATE_USER:
                cancelLoading();
                if (null != mConfirmDialog) {
                    mConfirmDialog.dismiss();
                }
                UserInfoBean accountBean = DataUtils.getUserInfo(mContext);
                if (accountBean.auth_flag == 1) {
                    RouteUtil.toBindCardCertificateActivity(CertificateIdCardActivity.this);
                    finish();
                    ToastUtil.showToast(mContext, "身份证件上传成功");
                }
                break;
        }
    }
}